<?php

// @author 3ogx <3ogx.com@gmail.com>

namespace Jushuitan;

use Illuminate\Support\Str;

class ApiRequest extends ErpBase
{
    use ErpHelpTrait;

    /**
     * ApiRequest constructor.
     *
     * @throws ErpException
     */
    public function __construct(array $config)
    {
        if (! isset($config['app_key'], $config['access_token'])) {
            throw new ErpException('缺少 access_token 等必要参数!');
        }

        $this->setConfig($config);
        $this->setPublicRequestParams($this->getConfig());
    }

    /**
     * @throws ErpException
     */
    public function __call($name, $arguments)
    {
        $callable = constant(__NAMESPACE__ . '\OpenApiURL::' . Str::upper($name));

        return $this->send($callable, ...$arguments);
    }

    /**
     * @return array
     */
    public function send($url, array $data)
    {
        $config         = $this->getConfig();
        $params         = $this->getPublicRequestParams();
        $params['biz']  = json_encode($data);
        $params['sign'] = $this->getSign($config['app_secret'], $params);
        $url            = $config['baseUrl'] . $url;

        return (new Client())->sendRequest($url, $params);
    }
}
